﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Web;
using WmsService.AOP;
using WmsService.Derived;
using WmsService.Exceptions;
using WmsService.Generate;
using WmsService.In;

namespace WmsService.BusinessLogic
{
    public interface IInvoiceAndPayApplyBillLogic
    {
        InvoiceBill GetInvoiceBill(string invoiceNo);

        [ValidateTokenCallHandler]
        void SaveInvoiceBill(InvoiceBill invoiceBill);

        [ValidateTokenCallHandler]
        void SaveInvoiceBillList(List<InvoiceBill> invoiceBills);

        [ValidateTokenCallHandler]
        [InvoiceBillHistoryCallHandler]
        void DeleteInvoiceBill(string invoiceNo);

        List<InvoiceBill> GetInvoiceBillsByCondition(string condition);

        List<ExtendInvoiceBill> GetExtendInvoiceBillsByCondition(string condition);

        List<ExtendInvoiceBillInStoreBill> GetExtendInvoiceBillInStoreBillsByCondition(string condition);

        InvoiceBillInStoreBill GetInvoiceBillInStoreBill(string invoiceNo, string inStoreBillID);

        InvoiceBillInStoreBillDtl GetInvoiceBillInStoreBillDtl(string invoiceNo, string inStoreBillDtlID);

        [ValidateTokenCallHandler]
        [InvoiceBillInStoreBillHistoryCallHandler]
        void CancelInStoreBillFromInvoiceBill(string invoiceNo, string inStoreBillID);

        [ValidateTokenCallHandler]
        void SaveInvoiceBillInStoreBill(InvoiceBillInStoreBill invoiceBillInStoreBill);

        [ValidateTokenCallHandler]
        void AddInvoiceBillInStoreBill(List<InvoiceBillInStoreBill> invoiceBillInStoreBills);

        List<InvoiceBillInStoreBill> GetInvoiceBillInStoreBillsByCondition(string condition);

        PayApplyBillInvoiceWrap GetPayApplyBillInvoiceWrap(string billID);

        [ValidateTokenCallHandler]
        void SavePayApplyBillInvoiceWrap(PayApplyBillInvoiceWrap payApplyBillInvoiceWrap);

        [ValidateTokenCallHandler]
        void AffirmPayApplyBillInvoice(string billID);

        [ValidateTokenCallHandler]
        void AttachInvoiceBills2PayApplyBill(string payApplyBillID, List<ExtendInvoiceBill> invoiceBills);

        [ValidateTokenCallHandler]
        [PayApplyBillDtlHistoryCallHandler]
        void DeleteInvoiceBillFromPayApplyBill(string payApplyBillID, string invoiceNo);

        [ValidateTokenCallHandler]
        [PayApplyBillDtlHistoryCallHandler]
        void DeleteInvoiceBillFromPayApplyBill(string payApplyBillID, InvoiceBill invoiceBill);

        List<PayApplyBill> GetPayApplyBillsByCondition(string condition);

        List<PayApplyBillDtl> GetPayApplyBillDtlsByCondition(string condition);

        PayApplyBillDtl GetPayApplyBillDtl(string payApplyBillID, string invoiceNo);

        PayApplyBill GetPayApplyBill(string payApplyBillID);

        [ValidateTokenCallHandler]
        string NewPayApplyBillItem(PayApplyBillItem payApplyBillItem);

        PayApplyBillItem GetPayApplyBillItem(string payApplyBillItemID);

        List<PayApplyBillItem> GetPayApplyBillItemsByCondition(string condition);

        [ValidateTokenCallHandler]
        void CancelPayApplyBillItem(string payApplyBillItemID);


        //================2010-10-28 added by henrik
        [ValidateTokenCallHandler]
        void AddInvoiceBillInStoreBillDtl(List<InvoiceBillInStoreBillDtl> invoiceBillInStoreBillDtls);

        [ValidateTokenCallHandler]
        [InvoiceBillInStoreBillDtlHistoryCallHandler]
        void CancelInStoreBillDtlFromInvoiceBill(string invoiceNo, string inStoreBillDtlID);
        //==================================
    }

    public class InvoiceAndPayApplyBillLogicImpl : LogicBase, IInvoiceAndPayApplyBillLogic
    {
        public InvoiceBill GetInvoiceBill(string invoiceNo)
        {
            var ctx = Factory.ContextFactory.Create();
            var query = from o in ctx.InvoiceBill
                        where o.InvoiceNo == invoiceNo
                        select o;
            var invoiceBill = query.FirstOrDefault();
            if (invoiceBill == null)
            {
                return null;
            }
            else
            {
                ctx.Detach(invoiceBill);
                return invoiceBill;
            }
        }

        public void SaveInvoiceBill(InvoiceBill invoiceBill)
        {
            var ctx = Factory.ContextFactory.Create();
            if (invoiceBill.WcfEntityState == EntityState.Added)
            {
                invoiceBill.CreateTime = DateTime.Now;
                invoiceBill.ExtDateTime1 = DateTime.Today;
                invoiceBill.CreateUserID = ContextUserID;
                invoiceBill.CreateUserName = ContextUserName;
            }
            else if (invoiceBill.WcfEntityState == EntityState.Modified)
            {
                var entity = GetInvoiceBill(invoiceBill.InvoiceNo);
                if(entity == null)
                {
                    Exceptions.ExceptionHandler.ThrowException("没有此发票："+invoiceBill.InvoiceNo);
                }
                else
                {
                    const string condition = " and InvoiceNo = '{0}'";
                    var payApplyBillDtls = GetPayApplyBillDtlsByCondition(string.Format(condition, invoiceBill.InvoiceNo));

                    if (payApplyBillDtls.Count > 0)
                    {
                        Exceptions.ExceptionHandler.ThrowException(String.Format(
                            "该发票已经属于付款申请单{0}，请先将发票从付款申请单上移除！", "[" + payApplyBillDtls[0].PayApplyBillID + "]"));
                    }

                    var list = this.GetInvoiceBillInStoreBillDtlsByCondition(string.Format(condition, invoiceBill.InvoiceNo));
                    if (list.Count > 0)
                    {
                        var inStoreBillDtl = this.GetInStoreBillDtl(list[0].InStoreBillDtlID);
                        Exceptions.ExceptionHandler.ThrowException(String.Format(
                            "入库单明细{0}已经分摊了该发票，修改前请先将发票从入库单上移除！", "[" + inStoreBillDtl.BillID + "：" + inStoreBillDtl.NewGoodsName + "]"));
                    }

                    invoiceBill.UpdateTime = DateTime.Now;
                    invoiceBill.UpdateUserID = ContextUserID;
                    invoiceBill.UpdateUserName = ContextUserName;
                }
             
            }
            else
            {
                return;
            }
            ctx.AddToInvoiceBill(invoiceBill);
            ctx.ObjectStateManager.ChangeObjectState(invoiceBill, invoiceBill.WcfEntityState);
            ctx.SaveChanges();
        }

        public void SaveInvoiceBillList(List<InvoiceBill> invoiceBills)
        {
            var ctx = Factory.ContextFactory.Create();
            foreach (var invoiceBill in invoiceBills)
            {
                if (invoiceBill.WcfEntityState == EntityState.Added)
                {
                    invoiceBill.CreateTime = DateTime.Now;
                    invoiceBill.CreateUserID = ContextUserID;
                    invoiceBill.CreateUserName = ContextUserName;
                }
                else if (invoiceBill.WcfEntityState == EntityState.Modified)
                {
                    invoiceBill.UpdateTime = DateTime.Now;
                    invoiceBill.UpdateUserID = ContextUserID;
                    invoiceBill.UpdateUserName = ContextUserName;
                }
                ctx.AddToInvoiceBill(invoiceBill);
                ctx.ObjectStateManager.ChangeObjectState(invoiceBill, invoiceBill.WcfEntityState);
            }
            ctx.SaveChanges();
        }

        public void DeleteInvoiceBill(string invoiceNo)
        {
            var invoiceBill = GetInvoiceBill(invoiceNo);
            if (invoiceBill == null)
            {
                Exceptions.ExceptionHandler.ThrowException(new Exception(String.Format("不存在发票{0}！", invoiceNo)));
            }
            var ctx = Factory.ContextFactory.Create();

            const string condition = " and InvoiceNo = '{0}'";
            var payApplyBillDtls = GetPayApplyBillDtlsByCondition(string.Format(condition, invoiceNo));

            if (payApplyBillDtls.Count > 0)
            {
                Exceptions.ExceptionHandler.ThrowException(String.Format(
                    "该发票已经属于付款申请单{0}，请先将发票从付款申请单上移除！", "[" + payApplyBillDtls[0].PayApplyBillID+ "]"));
            }
           
            var list = this.GetInvoiceBillInStoreBillDtlsByCondition(string.Format(condition, invoiceNo));
            if (list.Count > 0)
            {
                var inStoreBillDtl = this.GetInStoreBillDtl(list[0].InStoreBillDtlID);
                Exceptions.ExceptionHandler.ThrowException(String.Format(
                    "入库单明细{0}已经分摊了该发票，请先将发票从入库单上移除！","["+ inStoreBillDtl.BillID + "：" + inStoreBillDtl.NewGoodsName+"]"));
            }
            ctx.AddToInvoiceBill(invoiceBill);
            ctx.ObjectStateManager.ChangeObjectState(invoiceBill, EntityState.Deleted);
            ctx.SaveChanges();
        }

        public List<InvoiceBill> GetInvoiceBillsByCondition(string condition)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<InvoiceBill>("select * from  dbo.InvoiceBill where  1=1 " + condition).ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<ExtendInvoiceBill> GetExtendInvoiceBillsByCondition(string condition)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                //return ctx.ExecuteStoreQuery<ExtendInvoiceBill>("select * from (select  cast(0 as bit) as IsSelect, ib.*,p.PayApplyState,p.PayApplyDept,p.PayTypeName,isnull(p.TotalAmount,0) as TotalAmount from  dbo.InvoiceBill ib left join dbo.PayApplyBill p on ib.PayApplyBillID= p.PayApplyBillID) tmp where 1=1 " + condition).ToList();
                string sql = "select  cast(0 as bit) as IsSelect, ib.*,dbo.GetPayApplyBillDtlSumAmount(ib.InvoiceNo) as PayCompleteAmount  from dbo.InvoiceBill ib where 1=1 ";
                return ctx.ExecuteStoreQuery<ExtendInvoiceBill>(sql + condition).ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        private ExtendInvoiceBill GetExtendInvoiceBill(string invoiceNo)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                string sql = "select  cast(0 as bit) as IsSelect, ib.*,dbo.GetPayApplyBillDtlSumAmount(ib.InvoiceNo) as PayCompleteAmount  from dbo.InvoiceBill ib where ib.InvoiceNo='{0}' ";
                var q = ctx.ExecuteStoreQuery<ExtendInvoiceBill>(String.Format(sql, invoiceNo));
                var list = q.ToList();
                if (list.Count > 0)
                {
                    return list[0];
                }
                return null;
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<ExtendInvoiceBillInStoreBill> GetExtendInvoiceBillInStoreBillsByCondition(string condition)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<ExtendInvoiceBillInStoreBill>("select * from (select a.*,b.AmountTax,b.InStoreBillAmount from dbo.InvoiceBillInStoreBill a,dbo.InvoiceBill b where a.InvoiceNo = b.InvoiceNo) tmp where 1=1 " + condition).ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public InvoiceBillInStoreBill GetInvoiceBillInStoreBill(string invoiceNo, string inStoreBillID)
        {
            var ctx = Factory.ContextFactory.Create();
            var query = from o in ctx.InvoiceBillInStoreBill
                        where o.InStoreBillID == inStoreBillID
                              && o.InvoiceNo == invoiceNo
                        select o;
            return query.FirstOrDefault();
        }

        public InvoiceBillInStoreBillDtl GetInvoiceBillInStoreBillDtl(string invoiceNo, string inStoreBillDtlID)
        {
            var ctx = Factory.ContextFactory.Create();
            var query = from o in ctx.InvoiceBillInStoreBillDtl
                        where o.InStoreBillDtlID == inStoreBillDtlID
                              && o.InvoiceNo == invoiceNo
                        select o;
            return query.FirstOrDefault();
        }

        /// <summary>
        /// 将入库单从发票binding中去掉，也就是删除关系
        /// </summary>
        /// <param name="invoiceNo">发票号码</param>
        /// <param name="inStoreBillID">入库单号码</param>
        public void CancelInStoreBillFromInvoiceBill(string invoiceNo, string inStoreBillID)
        {
            var ctx = Factory.ContextFactory.Create();
            var query = from o in ctx.InvoiceBillInStoreBill
                        where o.InStoreBillID == inStoreBillID
                              && o.InvoiceNo == invoiceNo
                        select o;
            var invoiceBillInStoreBill = query.FirstOrDefault();
            if (invoiceBillInStoreBill == null)
            {
                Exceptions.ExceptionHandler.ThrowException(
                    new Exception(String.Format("不存在发票-入库单：发票号：{0}，入库单号：{1}", invoiceNo, inStoreBillID)));
            }
            else
            {

                var invoiceBill = GetInvoiceBill(invoiceNo);
                if (invoiceBill == null)
                {
                    Exceptions.ExceptionHandler.ThrowException(
                        new Exception(String.Format("不存在发票，发票号：{0}", invoiceNo)));
                }
                //if (!String.IsNullOrEmpty(invoiceBill.PayApplyBillID))
                //{
                //    Exceptions.ExceptionHandler.ThrowException(
                //        new Exception(String.Format("该发票已经属于付款单：{0}，要从入库单中移除发票，必须先将发票从付款单中移除！发票号：{1}", invoiceBill.PayApplyBillID, invoiceNo)));
                //}

                //由于需求改变，这里修改了判断发票是否存在付款单中的逻辑
                var payApplyBillDtls = this.GetPayApplyBillDtlsByCondition(String.Format(" and InvoiceNo ='{0}' ", invoiceBill.InvoiceNo));
                if (payApplyBillDtls.Count > 0)
                {
                    Exceptions.ExceptionHandler.ThrowException(
                       new Exception(String.Format("该发票已经属于付款单：{0}，要从入库单中移除发票，必须先将发票从付款单中移除！发票号：{1}", payApplyBillDtls[0].PayApplyBillID, invoiceNo)));
                }

                invoiceBill.InStoreBillAmount = invoiceBill.InStoreBillAmount - invoiceBillInStoreBill.PayAmountTax;

                ctx.AddToInvoiceBill(invoiceBill);
                ctx.ObjectStateManager.ChangeObjectState(invoiceBill, EntityState.Modified);

                ctx.Detach(invoiceBillInStoreBill);
                ctx.AddToInvoiceBillInStoreBill(invoiceBillInStoreBill);

                //删除对象
                ctx.ObjectStateManager.ChangeObjectState(invoiceBillInStoreBill, EntityState.Deleted);
                ctx.SaveChanges();
            }
        }

        public void SaveInvoiceBillInStoreBill(InvoiceBillInStoreBill invoiceBillInStoreBill)
        {
            var ctx = Factory.ContextFactory.Create();
            if (invoiceBillInStoreBill.WcfEntityState == EntityState.Added)
            {
                invoiceBillInStoreBill.CreateTime = DateTime.Now;
                invoiceBillInStoreBill.CreateUserID = ContextUserID;
                invoiceBillInStoreBill.CreateUserName = ContextUserName;
            }
            else if (invoiceBillInStoreBill.WcfEntityState == EntityState.Modified)
            {
                invoiceBillInStoreBill.UpdateTime = DateTime.Now;
                invoiceBillInStoreBill.UpdateUserID = ContextUserID;
                invoiceBillInStoreBill.UpdateUserName = ContextUserName;
            }
            ctx.AddToInvoiceBillInStoreBill(invoiceBillInStoreBill);
            //新增或者修改对象
            ctx.ObjectStateManager.ChangeObjectState(invoiceBillInStoreBill, invoiceBillInStoreBill.WcfEntityState);
            ctx.SaveChanges();
        }

        public void AddInvoiceBillInStoreBill(List<InvoiceBillInStoreBill> invoiceBillInStoreBills)
        {
            var ctx = Factory.ContextFactory.Create();
            foreach (var invoiceBillInStoreBill in invoiceBillInStoreBills)
            {
                if (invoiceBillInStoreBill.WcfEntityState == EntityState.Added)
                {
                    invoiceBillInStoreBill.CreateTime = DateTime.Now;
                    invoiceBillInStoreBill.CreateUserID = ContextUserID;
                    invoiceBillInStoreBill.CreateUserName = ContextUserName;
                    var invoiceBill = GetInvoiceBill(invoiceBillInStoreBill.InvoiceNo);
                    invoiceBill.InStoreBillAmount += invoiceBillInStoreBill.PayAmountTax;
                    if (invoiceBill.InStoreBillAmount > invoiceBill.AmountTax)
                    {
                        Exceptions.ExceptionHandler.ThrowException(new Exception("入库单分配总额超过发票的总金额！" + invoiceBill.InvoiceNo));
                    }
                    ctx.AddToInvoiceBill(invoiceBill);
                    //新增或者修改对象
                    ctx.ObjectStateManager.ChangeObjectState(invoiceBill, EntityState.Modified);
                }
                else if (invoiceBillInStoreBill.WcfEntityState == EntityState.Modified)
                {
                    Exceptions.ExceptionHandler.ThrowException(new Exception("不允许修改InvoiceBillInStoreBill对象，只准新增和删除！"));
                    //invoiceBillInStoreBill.UpdateTime = DateTime.Now;
                    //invoiceBillInStoreBill.UpdateUserID = ContextUserID;
                    //invoiceBillInStoreBill.UpdateUserName = ContextUserName;
                }
                ctx.AddToInvoiceBillInStoreBill(invoiceBillInStoreBill);
                //新增或者修改对象
                ctx.ObjectStateManager.ChangeObjectState(invoiceBillInStoreBill, invoiceBillInStoreBill.WcfEntityState);
            }
            ctx.SaveChanges();
        }

        public List<InvoiceBillInStoreBill> GetInvoiceBillInStoreBillsByCondition(string condition)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<InvoiceBillInStoreBill>("select * from  dbo.InvoiceBillInStoreBill where  1=1 " + condition).ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        private List<InvoiceBillInStoreBillDtl> GetInvoiceBillInStoreBillDtlsByCondition(string condition)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<InvoiceBillInStoreBillDtl>("select * from  dbo.InvoiceBillInStoreBillDtl where  1=1 " + condition).ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public PayApplyBillInvoiceWrap GetPayApplyBillInvoiceWrap(string billID)
        {
            try
            {
                var billWrap = new PayApplyBillInvoiceWrap();
                var ctx = Factory.ContextFactory.Create();
                var q = from c in ctx.PayApplyBill
                        where c.PayApplyBillID == billID
                        select c;
                var payApplyBill = q.FirstOrDefault();
                if (payApplyBill == null)
                {
                    return null;
                }

                ctx.Detach(payApplyBill);
                billWrap.FPayApplyBill = payApplyBill;
                //var q2 = from c in ctx.InvoiceBill
                //         where c.PayApplyBillID == billID
                //         select c;
                var qTmp = (from d in ctx.PayApplyBillDtl
                            where d.PayApplyBillID == billID
                            select d).ToList();
                var list = qTmp.Select(obj => obj.InvoiceNo).ToList();

                var q2 = from c in ctx.InvoiceBill
                         where list.Contains(c.InvoiceNo)
                         select c;
                billWrap.FInvoiceBillList = q2.ToList();
                foreach (var dtl in billWrap.FInvoiceBillList)
                {
                    ctx.Detach(dtl);
                }

                return billWrap;
            }
            catch (Exception ex)
            {
                ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void SavePayApplyBillInvoiceWrap(PayApplyBillInvoiceWrap payApplyBillInvoiceWrap)
        {
            try
            {
                if (payApplyBillInvoiceWrap.FPayApplyBill.PayApplyState != Constant.BillStateDraft)
                {
                    Exceptions.ExceptionHandler.ThrowException("非草稿状态的付款申请单单不能保存：" + payApplyBillInvoiceWrap.FPayApplyBill.PayApplyBillID);
                }

                var ctx = Factory.ContextFactory.Create();
                if (payApplyBillInvoiceWrap.FPayApplyBill.WcfEntityState == EntityState.Added)
                {
                    payApplyBillInvoiceWrap.FPayApplyBill.CREATETIME = DateTime.Now;
                    payApplyBillInvoiceWrap.FPayApplyBill.UPDATETIME = DateTime.Now;
                    payApplyBillInvoiceWrap.FPayApplyBill.CREATERUSERID = ContextUserID;
                    payApplyBillInvoiceWrap.FPayApplyBill.CREATERNAME = ContextUserName;
                    payApplyBillInvoiceWrap.FPayApplyBill.UPDATERNAME = ContextUserID;
                }
                else
                {
                    payApplyBillInvoiceWrap.FPayApplyBill.UPDATETIME = DateTime.Now;
                    payApplyBillInvoiceWrap.FPayApplyBill.UPDATERNAME = ContextUserID;
                }
                ctx.AddToPayApplyBill(payApplyBillInvoiceWrap.FPayApplyBill);
                ctx.ObjectStateManager.ChangeObjectState(payApplyBillInvoiceWrap.FPayApplyBill, payApplyBillInvoiceWrap.FPayApplyBill.WcfEntityState);
                if (payApplyBillInvoiceWrap.FInvoiceBillList != null && payApplyBillInvoiceWrap.FInvoiceBillList.Count > 0)
                {
                    foreach (var payApplyBillDtl in payApplyBillInvoiceWrap.FInvoiceBillList)
                    {
                        ctx.AddToInvoiceBill(payApplyBillDtl);
                        ctx.ObjectStateManager.ChangeObjectState(payApplyBillDtl, payApplyBillDtl.WcfEntityState);
                    }
                }
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                ExceptionHandler.ThrowException(ex);
            }
        }

        public void AffirmPayApplyBillInvoice(string billID)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();

                var wrap = GetPayApplyBillInvoiceWrap(billID);

                var payApplyBill = wrap.FPayApplyBill;

                if (payApplyBill.PayApplyState != Constant.BillStateDraft)
                {
                    Exceptions.ExceptionHandler.ThrowException("付款申请单状态为非草稿状态，不能确认：" + billID);
                }

                payApplyBill.PayApplyState = Constant.BillStateAffirm;//状态为确认

                ctx.AddToPayApplyBill(payApplyBill);
                ctx.ObjectStateManager.ChangeObjectState(payApplyBill, EntityState.Modified);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
            }
        }

        public void AttachInvoiceBills2PayApplyBill(string payApplyBillID, List<ExtendInvoiceBill> invoiceBills)
        {
            var payApplyBill = GetPayApplyBill(payApplyBillID);
            if (payApplyBill == null)
            {
                Exceptions.ExceptionHandler.ThrowException(new Exception("付款单不存在，也有可能没有保存！" + payApplyBillID));
            }

            if (payApplyBill.PayApplyState != Constant.BillStateDraft)
            {
                Exceptions.ExceptionHandler.ThrowException(new Exception("付款单状态必须是草稿才能添加发票！" + payApplyBillID));
            }

            var ctx = Factory.ContextFactory.Create();
            //var rowIDController = new RowIDController(RowIDType.PayApplyBillDtl, String.Format(" and PayApplyBillID ='{0}'", payApplyBillID));
            RowIDControllerBaseFactory baseFactory = new RowIDControllerBasePayApplyBillDtlFactory(payApplyBillID);
            var controller = baseFactory.GetRowIDController();

            foreach (var extendInvoiceBill in invoiceBills)
            {
                ExtendInvoiceBill temp = GetExtendInvoiceBill(extendInvoiceBill.InvoiceNo);

                if (temp == null)
                {
                    Exceptions.ExceptionHandler.ThrowException("该发票不存在，发票号码： " + extendInvoiceBill.InvoiceNo);
                }

                if (payApplyBill.ProviderCode != temp.ProviderCode)
                {
                    Exceptions.ExceptionHandler.ThrowException(new Exception("该发票和付款单的供应商不一致！付款单：" + payApplyBill.PayApplyBillID + "，发票号码： " + temp.InvoiceNo));
                }

                //发票可以属于多个付款单，所以下述控制删除
                //if (!String.IsNullOrEmpty(temp.PayApplyBillID))
                //{
                //    Exceptions.ExceptionHandler.ThrowException(new Exception("该发票已经属于付款单！" + temp.PayApplyBillID));
                //}

                //TODO
                if (temp.InStoreBillAmount != temp.AmountTax)
                {
                    Exceptions.ExceptionHandler.ThrowException(new Exception("该发票金额没有被入库单全部分摊，不能加入付款单！" + temp.InvoiceNo));
                }
                string condition = " and PayApplyBillID = '{0}' and InvoiceNo='{1}'";
                var payApplyBillDtls = GetPayApplyBillDtlsByCondition(String.Format(condition, payApplyBillID, temp.InvoiceNo));
                if (payApplyBillDtls.Count > 0)
                {
                    Exceptions.ExceptionHandler.ThrowException(new Exception("付款单已经包括该发票！" + temp.InvoiceNo));
                }
                //var dtl = PayApplyBillDtl.CreatePayApplyBillDtl(Guid.NewGuid().ToString(), payApplyBillID, controller.GetNextRowID(),
                //                                                            temp.AmountTax, Constant.IsValidTrue);


                //如果付款金额> 发票金额-已付金额，则抛异常
                if (temp.AmountTax - temp.PayCompleteAmount < extendInvoiceBill.PayApplyBillDtlPayAmountTax)
                {
                    Exceptions.ExceptionHandler.ThrowException(String.Format("付款金额不可超出发票剩余金额{0}，发票号：", temp.AmountTax - temp.PayCompleteAmount) + temp.InvoiceNo);
                }

                //付款金额不可为零
                if (extendInvoiceBill.PayApplyBillDtlPayAmountTax == 0)
                {
                    Exceptions.ExceptionHandler.ThrowException("付款金额不可为0，发票号：" + temp.InvoiceNo);
                }

                //创建付款明细，注意，金额为PayApplyBillDtlPayAmountTax
                var dtl = PayApplyBillDtl.CreatePayApplyBillDtl(Guid.NewGuid().ToString(), payApplyBillID, controller.GetNextRowID(),
                                                                        extendInvoiceBill.PayApplyBillDtlPayAmountTax, Constant.IsValidTrue);

                dtl.InvoiceNo = extendInvoiceBill.InvoiceNo;
                //明细的票面金额，记录发票的金额
                dtl.InvoiceAmount = extendInvoiceBill.AmountTax;
                ctx.AddToPayApplyBillDtl(dtl);
                ctx.ObjectStateManager.ChangeObjectState(dtl, EntityState.Added);

                //付款单金额加上该明细金额，也就是客户传入的金额
                payApplyBill.TotalAmount = (payApplyBill.TotalAmount ?? 0) +
                                           extendInvoiceBill.PayApplyBillDtlPayAmountTax;

                //如果报表输入的发票（人工填写）为空，则将当前发票号码填入
                //2010-10-27 added by henrik
                if (String.IsNullOrEmpty(payApplyBill.PayApplyInvoiceNoList))
                {
                    payApplyBill.PayApplyInvoiceNoList = dtl.InvoiceNo;
                }

                //temp.PayApplyBillID = payApplyBillID;
                temp.UpdateTime = DateTime.Now;
                temp.UpdateUserID = ContextUserID;
                temp.UpdateUserName = ContextUserName;
                var invoiceBill = Util.EntityChanger.ChangeEntityToBase<ExtendInvoiceBill, InvoiceBill>(temp);
                ctx.AddToInvoiceBill(invoiceBill);
                ctx.ObjectStateManager.ChangeObjectState(invoiceBill, EntityState.Modified);
            }

            ctx.AddToPayApplyBill(payApplyBill);
            ctx.ObjectStateManager.ChangeObjectState(payApplyBill, EntityState.Modified);

            ctx.SaveChanges();
        }

        public void DeleteInvoiceBillFromPayApplyBill(string payApplyBillID, string invoiceNo)
        {
            var getInvoiceBill = GetInvoiceBill(invoiceNo);
            if (getInvoiceBill == null)
            {
                Exceptions.ExceptionHandler.ThrowException(new Exception("该发票不存在！" + invoiceNo));
            }
            var payApplyBills =
            this.GetPayApplyBillsByCondition(String.Format(" and PayApplyBillID ='{0}'", payApplyBillID));
            if (payApplyBills.Count == 0)
            {
                Exceptions.ExceptionHandler.ThrowException(new Exception("该付款单不存在！" + payApplyBillID));
            }
            //if (String.IsNullOrEmpty(getInvoiceBill.PayApplyBillID))
            //{
            //    Exceptions.ExceptionHandler.ThrowException(new Exception("该发票不属于该付款单！" + payApplyBillID));
            //}
            var payApplyBill = payApplyBills[0];
            //string condition = " and PayApplyBillID = '{0}' and InvoiceNo='{1}'";
            var payApplyBillDtl = GetPayApplyBillDtl(payApplyBillID, getInvoiceBill.InvoiceNo);
            if (payApplyBillDtl == null)
            {
                Exceptions.ExceptionHandler.ThrowException(new Exception("付款单不包括该发票！" + invoiceNo));
            }
            var ctx = Factory.ContextFactory.Create();
            ctx.AddToPayApplyBillDtl(payApplyBillDtl);
            ctx.ObjectStateManager.ChangeObjectState(payApplyBillDtl, EntityState.Deleted);

            //付款单号码设置为''
            //getInvoiceBill.PayApplyBillID = String.Empty;
            getInvoiceBill.UpdateTime = DateTime.Now;
            getInvoiceBill.UpdateUserID = ContextUserID;
            getInvoiceBill.UpdateUserName = ContextUserName;
            ctx.AddToInvoiceBill(getInvoiceBill);
            ctx.ObjectStateManager.ChangeObjectState(getInvoiceBill, EntityState.Modified);

            //付款单总金额减去此金额
            payApplyBill.TotalAmount = (payApplyBill.TotalAmount ?? 0) - payApplyBillDtl.Amount;
            ctx.AddToPayApplyBill(payApplyBill);
            ctx.ObjectStateManager.ChangeObjectState(payApplyBill, EntityState.Modified);
            ctx.SaveChanges();
        }

        public void DeleteInvoiceBillFromPayApplyBill(string payApplyBillID, InvoiceBill invoiceBill)
        {
            DeleteInvoiceBillFromPayApplyBill(payApplyBillID, invoiceBill.InvoiceNo);
        }

        public List<PayApplyBill> GetPayApplyBillsByCondition(string condition)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<PayApplyBill>("select * from  dbo.PayApplyBill where  1=1 " + condition).ToList();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public List<PayApplyBillDtl> GetPayApplyBillDtlsByCondition(string condition)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<PayApplyBillDtl>("select * from  dbo.PayApplyBillDtl where  1=1 " + condition).ToList();

            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public PayApplyBillDtl GetPayApplyBillDtl(string payApplyBillID, string invoiceNo)
        {
            var ctx = Factory.ContextFactory.Create();
            var q = from c in ctx.PayApplyBillDtl
                    where c.PayApplyBillID == payApplyBillID
                    && c.InvoiceNo == invoiceNo
                    select c;
            var list = q.ToList();
            if (list.Count == 0)
                return null;
            ctx.Detach(list[0]);
            return list[0];
        }

        public PayApplyBill GetPayApplyBill(string payApplyBillID)
        {
            var ctx = Factory.ContextFactory.Create();
            var q = from c in ctx.PayApplyBill
                    where c.PayApplyBillID == payApplyBillID
                    select c;
            var payApplyBill = q.FirstOrDefault();
            if (payApplyBill == null)
            {
                return null;
            }
            ctx.Detach(payApplyBill);
            return payApplyBill;
        }

        public string NewPayApplyBillItem(PayApplyBillItem payApplyBillItem)
        {
            var ctx = Factory.ContextFactory.Create();

            //校验：付款金额不得大于该付款申请单的未付金额。
            PayApplyBill payApplyBill = GetPayApplyBill(payApplyBillItem.PayApplyBillID);
            if (payApplyBill == null)
            {
                Exceptions.ExceptionHandler.ThrowException("付款申请单为空：" + payApplyBillItem.PayApplyBillID);
            }

            if (payApplyBill.PayApplyState != Constant.BillStateAffirm)
            {
                Exceptions.ExceptionHandler.ThrowException("付款申请单没有确认，不能付款：" + payApplyBillItem.PayApplyBillID);
            }

            //如果付款金额大于该付款申请单的（总金额-已经付出金额）
            decimal notPayAmount = (payApplyBill.TotalAmount ?? 0) - (payApplyBill.HavePayTotalAmount ?? 0);
            if ((payApplyBillItem.PayAmount ?? 0) > notPayAmount)
            {
                Exceptions.ExceptionHandler.ThrowException(
                    String.Format("付款金额不得大于该付款申请单的未付金额！金额：{0}，未付金额：{1}", payApplyBillItem.PayAmount ?? 0, notPayAmount));
            }

            if ((payApplyBillItem.PayAmount ?? 0) == 0)
            {
                Exceptions.ExceptionHandler.ThrowException("付款金额不得为0！");
            }

            string payApplyBillItemID = Guid.NewGuid().ToString();

            RowIDControllerBaseFactory baseFactory = new RowIDControllerBasePayApplyBillItemFactory(payApplyBillItem.PayApplyBillID);
            var controller = baseFactory.GetRowIDController();

            payApplyBillItem.Idx = controller.GetNextRowID();
            payApplyBillItem.ItemState = Constant.ItemStateNormal;

            payApplyBillItem.PayApplyBillItemID = payApplyBillItemID;
            ctx.AddToPayApplyBillItem(payApplyBillItem);
            ctx.ObjectStateManager.ChangeObjectState(payApplyBillItem, EntityState.Added);

            payApplyBill.HavePayTotalAmount = (payApplyBill.HavePayTotalAmount ?? 0) + (payApplyBillItem.PayAmount ?? 0);

            if ((payApplyBill.HavePayTotalAmount ?? 0) == 0)
            {
                payApplyBill.PayState = Constant.PayNone;
            }
            else if ((payApplyBill.HavePayTotalAmount ?? 0) < payApplyBill.TotalAmount)
            {
                payApplyBill.PayState = Constant.PayPart;
            }
            else if ((payApplyBill.HavePayTotalAmount ?? 0) == payApplyBill.TotalAmount)
            {
                payApplyBill.PayState = Constant.PayComplete;
            }

            payApplyBill.PayTypeCode = payApplyBillItem.PayTypeCode;
            payApplyBill.PayTypeName = payApplyBillItem.PayTypeName;
            //付款项的付款时间为付款申请单最后付款时间
            payApplyBill.EndPayApplyDate = payApplyBillItem.PayTime;

            ctx.AddToPayApplyBill(payApplyBill);
            ctx.ObjectStateManager.ChangeObjectState(payApplyBill, EntityState.Modified);

            ctx.SaveChanges();
            return payApplyBillItemID;
        }

        public PayApplyBillItem GetPayApplyBillItem(string payApplyBillItemID)
        {
            var ctx = Factory.ContextFactory.Create();
            var q = from o in ctx.PayApplyBillItem
                    where o.PayApplyBillItemID == payApplyBillItemID
                    select o;
            return q.FirstOrDefault();
        }

        public List<PayApplyBillItem> GetPayApplyBillItemsByCondition(string condition)
        {
            try
            {
                var ctx = Factory.ContextFactory.Create();
                return ctx.ExecuteStoreQuery<PayApplyBillItem>("select * from  dbo.PayApplyBillItem where  1=1 " + condition + " order by Idx asc ").ToList();

            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ThrowException(ex);
                return null;
            }
        }

        public void CancelPayApplyBillItem(string payApplyBillItemID)
        {
            var ctx = Factory.ContextFactory.Create();
            var q = from o in ctx.PayApplyBillItem
                    where o.PayApplyBillItemID == payApplyBillItemID
                    select o;
            var payApplyBillItem = q.FirstOrDefault();

            if (payApplyBillItem == null)
            {
                Exceptions.ExceptionHandler.ThrowException("付款项为空：" + payApplyBillItemID);
            }
            ctx.Detach(payApplyBillItem);

            if (payApplyBillItem.ItemState != Constant.ItemStateNormal)
            {
                Exceptions.ExceptionHandler.ThrowException("状态不是[正常]的付款项是不能作废的：" + payApplyBillItem.PayApplyBillID + "！");
            }

            PayApplyBill payApplyBill = GetPayApplyBill(payApplyBillItem.PayApplyBillID);
            if (payApplyBill == null)
            {
                Exceptions.ExceptionHandler.ThrowException("付款申请单为空：" + payApplyBillItem.PayApplyBillID + "！");
            }
            payApplyBill.HavePayTotalAmount = (payApplyBill.HavePayTotalAmount ?? 0) - (payApplyBillItem.PayAmount ?? 0);

            if ((payApplyBill.HavePayTotalAmount ?? 0) == 0)
            {
                payApplyBill.PayState = Constant.PayNone;
            }
            else if ((payApplyBill.HavePayTotalAmount ?? 0) < payApplyBill.TotalAmount)
            {
                payApplyBill.PayState = Constant.PayPart;
            }
            else if ((payApplyBill.HavePayTotalAmount ?? 0) == payApplyBill.TotalAmount)
            {
                payApplyBill.PayState = Constant.PayComplete;
            }

            ctx.AddToPayApplyBill(payApplyBill);
            ctx.ObjectStateManager.ChangeObjectState(payApplyBill, EntityState.Modified);

            payApplyBillItem.ItemState = Constant.ItemStateCancelled;
            payApplyBillItem.CancelID = ContextUserID;
            payApplyBillItem.CancelName = ContextUserName;
            payApplyBillItem.CancelItemDate = DateTime.Now;

            ctx.AddToPayApplyBillItem(payApplyBillItem);
            ctx.ObjectStateManager.ChangeObjectState(payApplyBillItem, EntityState.Modified);

            ctx.SaveChanges();
        }

        #region IInvoiceAndPayApplyBillLogic Members

        private InStoreBillDtl GetInStoreBillDtl(string inStoreBillDtlID)
        {
            var ctx = Factory.ContextFactory.Create();
            var q = from c in ctx.InStoreBillDtl
                    where c.BillDtlID == inStoreBillDtlID
                    select c;
            var dtl = q.FirstOrDefault();
            if (dtl == null)
            {
                Exceptions.ExceptionHandler.ThrowException("不存在入库单明细：" + inStoreBillDtlID);
            }
            ctx.Detach(dtl);
            return dtl;
        }

        public void AddInvoiceBillInStoreBillDtl(List<InvoiceBillInStoreBillDtl> invoiceBillInStoreBillDtls)
        {
            var ctx = Factory.ContextFactory.Create();

            foreach (var invoiceBillInStoreBillDtl in invoiceBillInStoreBillDtls)
            {
                //if (invoiceBillInStoreBillDtl.WcfEntityState == EntityState.Added)
                //{
                var inStoreBillDtl = GetInStoreBillDtl(invoiceBillInStoreBillDtl.InStoreBillDtlID);
                var invoiceBill = GetInvoiceBill(invoiceBillInStoreBillDtl.InvoiceNo);

                if (inStoreBillDtl == null)
                {
                    Exceptions.ExceptionHandler.ThrowException(String.Format("不存在入库单明细，入库单明细号码：{0}", invoiceBillInStoreBillDtl.InStoreBillDtlID));
                }

                if (invoiceBill == null)
                {
                    Exceptions.ExceptionHandler.ThrowException(String.Format("不存在发票，发票号：{0}", invoiceBillInStoreBillDtl.InvoiceNo));
                }

                IInStoreBillLogic inStoreBillLogic = new InStoreBillLogicImpl();
                //入库单主表
                var inStoreBill = inStoreBillLogic.GetInStoreBill(inStoreBillDtl.BillID);

                if (inStoreBill == null)
                {
                    Exceptions.ExceptionHandler.ThrowException(String.Format("不存在入库单，入库单号：{0}", inStoreBillDtl.BillID));
                }

                //如果入库单为已经确认
                if (inStoreBill.ConfirmInvoiceFlag == Constant.ConfirmInvoiceFlagYes)
                {
                    Exceptions.ExceptionHandler.ThrowException(String.Format("入库单已经确认，不能再新增入库明细绑定的发票，入库单号：{0}", inStoreBillDtl.BillID));
                }


                invoiceBillInStoreBillDtl.CreateTime = DateTime.Now;
                invoiceBillInStoreBillDtl.CreateUserID = ContextUserID;
                invoiceBillInStoreBillDtl.CreateUserName = ContextUserName;

                invoiceBill.InStoreBillAmount += invoiceBillInStoreBillDtl.InvoiceDtlAmountTax;
                if (invoiceBill.InStoreBillAmount > invoiceBill.AmountTax)
                {
                    Exceptions.ExceptionHandler.ThrowException(new Exception("入库单明细分配总额超过发票的总金额！" + invoiceBill.InvoiceNo));
                }

                inStoreBillDtl.InvoiceDtlTotalAmountTax = (inStoreBillDtl.InvoiceDtlTotalAmountTax ?? 0) + invoiceBillInStoreBillDtl.InvoiceDtlAmountTax;
                if (inStoreBillDtl.InvoiceDtlTotalAmountTax > inStoreBillDtl.AmountTax)
                {
                    Exceptions.ExceptionHandler.ThrowException(String.Format("发票明细分摊的总金额之和{0}大于入库单明细含税总额{1}！", inStoreBillDtl.InvoiceDtlTotalAmountTax, inStoreBillDtl.AmountTax));
                }

                if (String.IsNullOrEmpty(inStoreBillDtl.InvoiceNoList))
                {
                    inStoreBillDtl.InvoiceNoList = invoiceBill.InvoiceNo;
                }
                else
                {
                    inStoreBillDtl.InvoiceNoList += ("/" + invoiceBill.InvoiceNo);
                }

                //放入入库单明细
                ctx.AddToInStoreBillDtl(inStoreBillDtl);
                ctx.ObjectStateManager.ChangeObjectState(inStoreBillDtl, EntityState.Modified);

                //放入发票
                ctx.AddToInvoiceBill(invoiceBill);
                //新增或者修改对象
                ctx.ObjectStateManager.ChangeObjectState(invoiceBill, EntityState.Modified);
                //}
                //else if (invoiceBillInStoreBillDtl.WcfEntityState == EntityState.Modified)
                //{
                //    Exceptions.ExceptionHandler.ThrowException(new Exception("不允许修改InvoiceBillInStoreBillDtl对象，只准新增和删除！"));
                //}
                ctx.AddToInvoiceBillInStoreBillDtl(invoiceBillInStoreBillDtl);
                //新增或者修改对象
                ctx.ObjectStateManager.ChangeObjectState(invoiceBillInStoreBillDtl, invoiceBillInStoreBillDtl.WcfEntityState);
            }
            try
            {
                ctx.SaveChanges();
            }
            catch (Exception exception)
            {
                ExceptionHandler.ThrowException(exception);
            }
        }

        public void CancelInStoreBillDtlFromInvoiceBill(string invoiceNo, string inStoreBillDtlID)
        {

            var ctx = Factory.ContextFactory.Create();
            var query = from o in ctx.InvoiceBillInStoreBillDtl
                        where o.InStoreBillDtlID == inStoreBillDtlID
                              && o.InvoiceNo == invoiceNo
                        select o;
            var invoiceBillInStoreBillDtl = query.FirstOrDefault();
            if (invoiceBillInStoreBillDtl == null)
            {
                Exceptions.ExceptionHandler.ThrowException(
                    new Exception(String.Format("不存在发票-入库单明细：发票号：{0}，入库单明细号码：{1}", invoiceNo, inStoreBillDtlID)));
            }
            else
            {
                var inStoreBillDtl = GetInStoreBillDtl(invoiceBillInStoreBillDtl.InStoreBillDtlID);
                var invoiceBill = GetInvoiceBill(invoiceNo);

                if (inStoreBillDtl == null)
                {
                    Exceptions.ExceptionHandler.ThrowException(String.Format("不存在入库单明细，入库单明细号码：{0}", invoiceBillInStoreBillDtl.InStoreBillDtlID));
                }

                if (invoiceBill == null)
                {
                    Exceptions.ExceptionHandler.ThrowException(String.Format("不存在发票，发票号：{0}", invoiceNo));
                }

                IInStoreBillLogic inStoreBillLogic = new InStoreBillLogicImpl();
                //入库单主表
                var inStoreBill = inStoreBillLogic.GetInStoreBill(inStoreBillDtl.BillID);

                if (inStoreBill == null)
                {
                    Exceptions.ExceptionHandler.ThrowException(String.Format("不存在入库单，入库单号：{0}", inStoreBillDtl.BillID));
                }

                //如果入库单为已经确认
                if (inStoreBill.ConfirmInvoiceFlag == Constant.ConfirmInvoiceFlagYes)
                {
                    Exceptions.ExceptionHandler.ThrowException(String.Format("入库单已经确认，不能再移除入库明细绑定的发票，入库单号：{0}", inStoreBillDtl.BillID));
                }

                //由于需求改变，这里修改了判断发票是否存在付款单中的逻辑
                var payApplyBillDtls = this.GetPayApplyBillDtlsByCondition(String.Format(" and InvoiceNo ='{0}' ", invoiceBill.InvoiceNo));
                if (payApplyBillDtls.Count > 0)
                {
                    Exceptions.ExceptionHandler.ThrowException(
                      String.Format("该发票已经属于付款单：{0}，要从入库单明细中移除发票，必须先将发票从付款单中移除！发票号：{1}", payApplyBillDtls[0].PayApplyBillID, invoiceNo));
                }

                inStoreBillDtl.InvoiceDtlTotalAmountTax = (inStoreBillDtl.InvoiceDtlTotalAmountTax ?? 0) - invoiceBillInStoreBillDtl.InvoiceDtlAmountTax;

                if (!String.IsNullOrEmpty(inStoreBillDtl.InvoiceNoList))
                {
                    string[] strings = inStoreBillDtl.InvoiceNoList.Split('/');
                    string newInvoiceNos = "";
                    for (int idx = 0; idx < strings.Length; idx++)
                    {
                        if (strings[idx] != invoiceNo)
                        {
                            if (String.IsNullOrEmpty(newInvoiceNos))
                            {
                                newInvoiceNos = strings[idx];
                            }
                            else
                            {
                                newInvoiceNos += (("/" + strings[idx]));
                            }
                        }
                    }
                    inStoreBillDtl.InvoiceNoList = newInvoiceNos;
                }

                ctx.AddToInStoreBillDtl(inStoreBillDtl);
                ctx.ObjectStateManager.ChangeObjectState(inStoreBillDtl, EntityState.Modified);

                invoiceBill.InStoreBillAmount = invoiceBill.InStoreBillAmount - invoiceBillInStoreBillDtl.InvoiceDtlAmountTax;

                ctx.AddToInvoiceBill(invoiceBill);
                ctx.ObjectStateManager.ChangeObjectState(invoiceBill, EntityState.Modified);

                ctx.Detach(invoiceBillInStoreBillDtl);
                ctx.AddToInvoiceBillInStoreBillDtl(invoiceBillInStoreBillDtl);

                //删除对象
                ctx.ObjectStateManager.ChangeObjectState(invoiceBillInStoreBillDtl, EntityState.Deleted);
                ctx.SaveChanges();
            }
        }

        #endregion
    }
}